The Amazing Kitty

Put Kitty Through Her Paces

The graphics techniques used here are explored in other recipes; what we're doing here is looking at the string.split() script method as a way of parsing user input into commands.

Kitty expects one- or two-word commands: go left or simply left. Other possible directions are up, down, and right. (When you tell Kitty to move left or right, she moves to your left or right, not hers!) Kitty understands compass directions, too.

If Kitty can follow your direction, she responds with a comment; if not, she lets you know something is in her way. And, unlike most cats, Kitty never ignores a command!

Discussion

Every time you press the Tell Kitty button, the script function TellKitty() retrieves the typed-in command in the form field and uses string.split() to break it into words.
function TellKitty()
{
    var verb = '', 
        direction = '';
    var instruction = document.form0.kittySuggestion.value;
    // If it's a one-word instruction, then there aren't
    // any spaces in the string.
    if(instruction.indexOf(' ') == -1) {
        direction = instruction.toLowerCase();
        verb = 'go';
    } else {
        var iArray  = instruction.split(' ');
        verb        = iArray[0].toString();
        direction   = iArray[iArray.length-1].toString();
        verb        = verb.toLowerCase();
        direction   = direction.toLowerCase();
    }
    if(verb == 'go') {
        switch(direction.charAt(0)) {
            case 'u':
            case 'n':
                GoUp();
                break;
            case 'l':
            case 'w':
                GoLeft();
                break;
            case 'r':
            case 'e':
                GoRight();
                break;
            case 'd':
            case 's':
                GoDown();
                break;
            default:
                KittySez("I don't know which way you're telling me to go.");
        }
    } else {
        KittySez("I don't know the word \""+verb+".\"");
    }
}
This isn't a particularly brilliant parser, but it gets the job done. When the parser detects a single-word command, it assumes that what it found is a direction, and copies the word into the direction variable; it then sets the value of verb to "go" so that the rest of the parser logic won't have, um, kittens.

There's another all-purpose trick that you should learn, too: notice that when Kitty wants to "say" something, that the script uses the function KittySez() to perform the operation. This is because Netscape Navigator doesn't support the same Document Object Model as Internet Explorer; if you're using IE, you see a nice string on the screen, but if you're using Navigator, you see Kitty's comments in a form field. KittySez() hides the differences from you when you're writing the parser, so you don't duplicate the if(Netscape)...else if(IE) checks over and over.

Copyright ©2000 by Charles River Media, All Rights Reserved